﻿using System.Collections.Generic;
using UnityEngine;

namespace Framework
{
    public class WorldAsyncLoader : MonoBehaviour
    {
        [SerializeField]
        List<WorldAsyncLoaderObserver> observers = new List<WorldAsyncLoaderObserver>();

        World world = new World();
        HashSet<Vector3Int> renderSet = new();

        private void Update()
        {
            var newSet = new HashSet<Vector3Int>();
            foreach (var observer in observers)
            {
                int x1 = CoordConvert.PosX2Cnk(observer.transform.position.x - observer.VisualRange);
                int x2 = CoordConvert.PosX2Cnk(observer.transform.position.x + observer.VisualRange);
                //int y1 = CoordConvert.PosX2Cnk(observer.transform.position.y - observer.VisualRange);
                //int y2 = CoordConvert.PosX2Cnk(observer.transform.position.y + observer.VisualRange);
                int z1 = CoordConvert.PosX2Cnk(observer.transform.position.z - observer.VisualRange);
                int z2 = CoordConvert.PosX2Cnk(observer.transform.position.z + observer.VisualRange);

                for (int x = x1; x < x2 + 1; x++)
                {
                    for (int z = z1; z < z2 + 1; z++)
                    {
                        newSet.Add(new Vector3Int(x, 0, z));
                    }
                }
            }
            var addSet = new HashSet<Vector3Int>(newSet);
            addSet.ExceptWith(renderSet);
            renderSet.ExceptWith(newSet);
            foreach (var index in addSet)
            {
                WorldRenderManager.DisplayChunk(world[index]);
            }
            foreach (var index in renderSet)
            {
                WorldRenderManager.HideChunk(world[index]);
            }
            renderSet = newSet;
        }

        private void OnGUI()
        {
            GUILayout.BeginHorizontal();
            GUILayout.Label($"Render Chunk:{renderSet.Count}");
            GUILayout.Label($"Render Block:{renderSet.Count * Chunk.size.x * Chunk.size.y * Chunk.size.z}");
            GUILayout.EndHorizontal();
        }
    }
}
